const CourseModel = require('../models/course')
const ScoreModel = require('../models/score')
class Score {
  // 课程添加
  async add(ctx) {
    const { user } = ctx.state
    if (user.role == 0) {
      const data = ctx.request.body
      const course = new CourseModel({
        courseName: data.courseName,
        teacher: data.teacher,
        remark: data.remark,
        credit: data.credit
      })
      const result = await course.save()
      return result !== null
        ? ctx.send(null, '创建课程成功')
        : ctx.sendError('000002', '创建课程失败功')
    } else {
      return ctx.sendError(0, '没有权限')
    }
  }

  // 课程修改
  async update(ctx) {
    const { user } = ctx.state
    if (user.role == 0) {
      const { status, courseId } = ctx.request.body
      const res = await CourseModel.updateOne({ _id: courseId }, { status })
      if (res) {
        return ctx.send('课程状态修改成功')
      } else {
        return ctx.sendError('000002', '课程状态修改失败')
      }
    } else if (user.role == 2) {
      const { courseId, userId, flag } = ctx.request.body
      if (flag == 'add') {
        const result = await CourseModel.findOne({
          _id: courseId,
          students: { $in: userId }
        })
        if (result) {
          return ctx.sendError('000002', '该课程已选')
        } else {
          const res = await CourseModel.updateOne(
            {
              _id: courseId,
              status: 1
            },
            {
              $addToSet: {
                students: userId
              }
            }
          )
          if (res) {
            return ctx.send('选课成功')
          } else {
            return ctx.sendError('000002', '选课失败')
          }
        }
      } else {
        const result = await CourseModel.findOne({
          _id: courseId,
          students: { $in: userId }
        })
        if (result) {
          const res = await CourseModel.updateOne(
            {
              _id: courseId
            },
            {
              $pull: {
                students: userId
              }
            }
          )
          if (res) {
            return ctx.send('选课取消成功')
          } else {
            return ctx.sendError('000002', '选课取消成功')
          }
        } else {
          return ctx.sendError('000002', '该课程未选')
        }
      }
    }else if(user.role == 1){
      const { status, courseId } = ctx.request.body
      if(status==2){
        const res = await CourseModel.findOneAndUpdate({ _id: courseId }, { status })
        const resData = await Promise.all(res.students.map(student => {
          const score= new ScoreModel({ teacher:user.id,course:courseId,student })
          return score.save()
        }));
        if (resData) {
          return ctx.send('开课成功')
        } else {
          return ctx.sendError('000002', '课程状态修改失败')
        }
      }else{
        return ctx.sendError('000002', '没有权限')
      }
    }
  }

  // 课程删除
  async del(ctx) {
    const { user } = ctx.state
    if (user.role == 0) {
      const { courseId } = ctx.request.body
      await CourseModel.findById(courseId)
        .then(data => data.remove())
        .catch(err => {
          return ctx.sendError(0, '删除失败，服务器错误')
        })
      return ctx.send('删除成功')
    } else {
      return ctx.sendError(0, '没有权限')
    }
  }
  // 课程查询
  async inquire(ctx) {
    const { user } = ctx.state
    let { pageNum = 1, pageSize = 10 } = ctx.request.body
    pageNum--
    pageNum = parseInt(pageNum)
    pageSize = parseInt(pageSize)
    if (user.role == 0) {
      const maxNum = await CourseModel.estimatedDocumentCount((err, num) =>
        err ? console.log(err) : num
      )
      await CourseModel.find()
        .populate({
          path: 'teacher',
          select: '_id number username'
        })
        .skip(pageNum * pageSize)
        .limit(pageSize)
        .then(data => {
          return ctx.send({ courseLists: data, totalPage: maxNum })
        })
        .catch(err => {
          return ctx.sendError('000002')
        })
    } else if (user.role == 2) {
      const maxNum = await CourseModel.find({
        status: {$ne:0},
        // students: { $ne: user.id }
      }).countDocuments(true)
      const result = await CourseModel.find({
        status: {$ne:0},
        // students: { $ne: user.id }
      }).populate({
        path: 'teacher',
        select: '_id number username'
      })
        .skip(pageNum * pageSize)
        .limit(pageSize)
      if (result) {
        return ctx.send({ courseLists: result, totalPage: maxNum })
      } else {
        return ctx.sendError('000002', '查询失败')
      }
    } else if (user.role == 1) {
      const maxNum = await CourseModel.find({
        teacher: { _id: user.id },status:{$ne:0}
      }).countDocuments(true)
      const result = await CourseModel.find({
        teacher: { _id: user.id },status:{$ne:0}
      }).populate({
        path: 'teacher',
        select: '_id number username'
      })
        .skip(pageNum * pageSize)
        .limit(pageSize)
      if (result) {
        return ctx.send({ courseLists: result, totalPage: maxNum })
      } else {
        return ctx.sendError('000002', '查询失败')
      }
    }
  }
}

module.exports = new Score()
